﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;

/// <summary>
/// Methods for managing thumbnail images
/// </summary>
public static class ThumbNails
{
    /// <summary>
    /// Returns a thumnail version of an image if the original image is larger than the specified maximum width
    /// </summary>
    /// <param name="image">Path to the image to be resized</param>
    /// <param name="thumbWidth">Maximum width of the resulting thumbnail</param>
    /// <returns>byte array</returns>
    public static byte[] GenerateTumbnail(string image, double thumbWidth) {
        try {
            using (var originalImage = Image.FromFile(image)) {
                var thumbHeight = originalImage.Width > thumbWidth ? (thumbWidth / originalImage.Width) * originalImage.Height : originalImage.Height;
                thumbWidth = originalImage.Width > thumbWidth ? thumbWidth : originalImage.Width;
                using (var bmp = new Bitmap((int)thumbWidth, (int)thumbHeight)) {
                    bmp.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
                    using (var graphic = Graphics.FromImage(bmp)) {
                        graphic.SmoothingMode = SmoothingMode.AntiAlias;
                        graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;

                        var rectangle = new Rectangle(0, 0, (int)thumbWidth, (int)thumbHeight);
                        graphic.DrawImage(originalImage, rectangle, 0, 0, originalImage.Width, originalImage.Height, GraphicsUnit.Pixel);
                        var ms = new MemoryStream();
                        bmp.Save(ms, originalImage.RawFormat);
                        return ms.GetBuffer();
                    }
                }
            }
        }
        catch (Exception ex) {
            throw (ex);
        }
    }
}